//
//  AddAnntionView.m
//  markmap
//
//  Created by 甘世清 on 2024/3/28.
//

#import "AddAnntionView.h"
#import "AddAnntionImageCollectionViewCell.h"
#import "AddModel.h"
#import "AuthorityView.h"

@implementation AddAnntionView

- (void)SQ_UIViewForSelfView{
    self.layer.cornerRadius = 48;
    self.backgroundColor = SQColor(@"#4A4A4A");
    
    [self addSubview:self.addressLabel];
    [self.addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.width.mas_equalTo(SCREEN_WIDETH-60);
        make.top.equalTo(self).offset(17);
    }];
    
    UILabel * label1 = [[UILabel alloc]init];
    label1.text = SQNSLocalString(@"标题");
    label1.textColor = UIColor.whiteColor;
    label1.font = FONT_REGULAR(13);
    [self addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(12);
        make.top.equalTo(self.addressLabel.mas_bottom).offset(25);
    }];
    [self addSubview:self.textField];
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(46);
        make.top.equalTo(label1);
        make.right.equalTo(self.mas_right).offset(-30);
        make.height.mas_equalTo(44);
    }];
    
    UILabel * label2 = [[UILabel alloc]init];
    label2.text = SQNSLocalString(@"描述");
    label2.textColor = UIColor.whiteColor;
    label2.font = FONT_REGULAR(13);
    [self addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(12);
        make.top.equalTo(label1.mas_bottom).offset(40);
    }];
    
    [self addSubview:self.fsTextView];
    [self.fsTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(46);
        make.top.equalTo(label2);
        make.right.equalTo(self.mas_right).offset(-30);
        make.height.mas_equalTo(120);
    }];
    
    UILabel * label3 = [[UILabel alloc]init];
    label3.text = SQNSLocalString(@"图片");
    label3.textColor = UIColor.whiteColor;
    label3.font = FONT_REGULAR(13);
    [self addSubview:label3];
    [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(12);
        make.top.equalTo(label2.mas_bottom).offset(112);
    }];
    
    [self.collectionView registerClass:[AddAnntionImageCollectionViewCell class] forCellWithReuseIdentifier:@"AddAnntionImageCollectionViewCell"];
    self.collectionView.alwaysBounceVertical = NO;
    [self addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.top.equalTo(label3.mas_bottom).offset(8);
        make.height.mas_equalTo(90);
    }];
    AddModel * model = [AddModel new];
    model.isAdd = YES;
    [self.jsonArray addObject:model];
    [self.collectionView reloadData];
    
    UILabel * label4 = [[UILabel alloc]init];
    label4.text = SQNSLocalString(@"权限");
    label4.textColor = UIColor.whiteColor;
    label4.font = FONT_REGULAR(13);
    [self addSubview:label4];
    [label4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(12);
        make.top.equalTo(label3.mas_bottom).offset(112);
    }];
    
    [self addSubview:self.typeBtn];
    [self.typeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(46);
        make.top.equalTo(label4);
        make.width.mas_equalTo(64);
        make.height.mas_equalTo(26);
    }];
    WS(weakSelf);
    [self.typeBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf SQ_ShowAuthority];
    }];
    
    [self addSubview:self.addButton];
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.top.equalTo(label4.mas_bottom).offset(50);
        make.width.mas_equalTo(SCREEN_WIDETH-60);
        make.height.mas_equalTo(45);
    }];
}
//上传定位点确认
-(void)SQ_addAnntionForMap{
    if (![self.textField.text isNotEmpty]) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"请输入标题")];
        return;
    } else  if (self.textField.text.length<2 ||self.textField.text.length > 10){
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"标题为2~10字符")];
        return;
    }
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:self.textField.text forKey:@"title"];
    if ([self.fsTextView.formatText isNotEmpty]) {
        [dic setObject:self.fsTextView.formatText forKey:@"remark"];
    }
    [dic setObject:@(self.typeBtn.tag) forKey:@"isPublic"];
    NSString *city = self.place.locality;
    [dic setObject:@(self.place.location.coordinate.latitude) forKey:@"lat"];
    [dic setObject:@(self.place.location.coordinate.longitude) forKey:@"lng"];
    if ([city isNotEmpty]) {
        [dic setObject:self.place.locality forKey:@"city"];
        NSString * address = [NSString stringWithFormat:@"%@%@%@%@",self.place.country,self.place.locality,self.place.thoroughfare,self.place.name];
        [dic setObject:address forKey:@"address"];
       
    } else {
        [dic setObject:self.place.administrativeArea forKey:@"city"];
        NSString * address = [NSString stringWithFormat:@"%@%@%@%@",self.place.country,self.place.administrativeArea,self.place.thoroughfare,self.place.name];
        [dic setObject:address forKey:@"address"];
    }
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    WS(weakSelf);
    [HttpTool post:Url23 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        PointModel * model = [PointModel mj_objectWithKeyValues:httpModel.data];
        if (self.addSuccessfulBlock&&self.jsonArray.count<=1) {
            self.addSuccessfulBlock();
        }else{
            [weakSelf SQ_UpImageUrl:model];
        }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
 
   
}
-(void)SQ_UpImageUrl:(PointModel*)mo{
   
    NSMutableArray * imageArray = [[NSMutableArray alloc]init];
    for (AddModel * model in self.jsonArray) {
        if (model.isAdd) {
            continue;
        }
        [YJProgressHUD SQ_showMsgWithoutView:@""];
        [HttpTool SQ_Image:model.addImage successBlock:^(BaseModel * _Nonnull httpModel) {
            [imageArray addObject:httpModel.data];
            if (imageArray.count+1 == self.jsonArray.count) {
              //上传完成
              [self SQ_url:httpModel.data mo:mo array:imageArray];
            }
        } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
            [YJProgressHUD showMsgWithoutView:httpModel.message];
        }];
    }
}
-(void)SQ_url:(NSString*)url mo:(PointModel*)mo array:(NSMutableArray*)imageArray{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[imageArray componentsJoinedByString:@","] forKey:@"urls"];
    [dic setObject:mo.userid forKey:@"pid"];
    [HttpTool post:Url12 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
    
        if (self.addSuccessfulBlock) {
                self.addSuccessfulBlock();
           }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}
 

- (void)setPlace:(CLPlacemark *)place{
    _place = place;
}


#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.jsonArray.count >3) {
        return 3;
    }
    return self.jsonArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    AddAnntionImageCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddAnntionImageCollectionViewCell" forIndexPath:indexPath];
    AddModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    model.index = self.jsonArray.count - 1;
    cell.model = model;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(88, 88);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 12;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 46, 0, 12);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    AddModel * model = [self.jsonArray objectAtIndex:indexPath.item];
   
    if (model.isAdd) {
        [self SQ_headerButtonClick];
    }else{
        [self SQ_deletedButtonClick:indexPath];
    }
    
}
-(void)SQ_deletedButtonClick:(NSIndexPath*)indexPath{
    WS(weakSelf);
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"是否删除该照片") message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * co1 = [UIAlertAction actionWithTitle:SQNSLocalString(@"删除") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.jsonArray removeObjectAtIndex:indexPath.item];
        [weakSelf.collectionView reloadData];
    }];
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co1];
    [alert addAction:co2];
    [[Manager SQ_getCurrentViewController] presentViewController:alert animated:YES completion:nil];
}
 
-(void)SQ_headerButtonClick{
    WS(weakSelf);
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"选择照片") message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * co0 = [UIAlertAction actionWithTitle:SQNSLocalString(@"拍照") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf SQ_leftButtonClick];
    }];
    UIAlertAction * co1 = [UIAlertAction actionWithTitle:SQNSLocalString(@"相册") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf SQ_rightButtonClick];
    }];
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co0];
    [alert addAction:co1];
    [alert addAction:co2];
    [[Manager SQ_getCurrentViewController] presentViewController:alert animated:YES completion:nil];
}

-(void)SQ_leftButtonClick{
    WS(weakSelf);
    _imagePickerVc = [[UIImagePickerController alloc] init];
    _imagePickerVc.delegate = self;
    _imagePickerVc.allowsEditing = YES;
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
        weakSelf.imagePickerVc.sourceType = sourceType;
        [[Manager SQ_getCurrentViewController] presentViewController:weakSelf.imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    WS(weakSelf);
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *photo = [info objectForKey:UIImagePickerControllerEditedImage];
        if (photo == nil)
            {
                photo = [info objectForKey:UIImagePickerControllerOriginalImage];
            }
        [weakSelf SQ_caijian:photo];
    }else
    {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"相册数据异常")];
    }
}


-(void)SQ_rightButtonClick{
    WS(weakSelf);
    TZImagePickerController * vc = [[TZImagePickerController alloc]init];
    vc.maxImagesCount = 4-self.jsonArray.count;
    [[Manager SQ_getCurrentViewController] presentViewController:vc animated:YES completion:nil];
    [vc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        for (UIImage * image in photos) {
            [weakSelf SQ_caijian:image];
        }
    }];
}

//添加图片到列表
-(void)SQ_caijian:(UIImage*)image {
    AddModel * model = [AddModel new];
    model.addImage = image;
    [self.jsonArray insertObject:model atIndex:0];
    [self.collectionView reloadData];
    
}

-(void)SQ_ShowAuthority{
    AuthorityView* vc = [[AuthorityView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, 200)];
    vc.index = self.typeBtn.tag;
    LSTPopView * pop = [LSTPopView initWithCustomView:vc parentView:nil popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleBottom;
    [pop pop];
    LSTPopViewWK(pop)
    [pop setBgClickBlock:^{
        [wk_pop dismiss];
    }];
    WS(weakSelf);
    [vc.gongkai setTouchBlock:^(SQCustomButton * _Nonnull button) {
        weakSelf.typeBtn.tag = 1;
        weakSelf.typeBtn.text = SQNSLocalString(@"公开");
        weakSelf.typeBtn.textColor = SQColor(@"#FF33B6");
        weakSelf.typeBtn.layer.borderColor = SQColor(@"#FF33B6").CGColor;
        [wk_pop dismiss];
    }];
    [vc.shiren setTouchBlock:^(SQCustomButton * _Nonnull button) {
        weakSelf.typeBtn.tag = 0;
        weakSelf.typeBtn.text = SQNSLocalString(@"私人");
        weakSelf.typeBtn.textColor = SQColor(@"#33FFFC");
        weakSelf.typeBtn.layer.borderColor = SQColor(@"#33FFFC").CGColor;
        [wk_pop dismiss];
    }];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.textField resignFirstResponder];
    return YES;
}

- (UITextField *)textField{
    if (!_textField) {
        _textField = [[UITextField alloc]init];
        _textField.backgroundColor = SQColor(@"#6B6B6B");
        _textField.textColor = UIColor.whiteColor;
        _textField.font = FONT_REGULAR(14);
        _textField.delegate = self;
        _textField.returnKeyType = UIReturnKeyDone;
        _textField.layer.masksToBounds = YES;
        _textField.layer.cornerRadius = 8;
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 6, 40)];
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.leftView = bgView;
    }
    return _textField;
}

-(FSTextView*)fsTextView{
    if (!_fsTextView) {
        _fsTextView = [FSTextView textView];
        _fsTextView.font = FONT_REGULAR(14);
        _fsTextView.textColor = UIColor.whiteColor;
        _fsTextView.layer.cornerRadius = 8;
//        _fsTextView.placeholder =SQNSLocalString(@"这里输入你要反馈的问题...");
        _fsTextView.placeholderColor = UIColor.whiteColor;
        _fsTextView.backgroundColor = SQColor(@"#6B6B6B");
        _fsTextView.maxLength = 300;
    }
    return _fsTextView;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.userInteractionEnabled = YES;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}
-(NSMutableArray*)jsonArray
{
    if (!_jsonArray) {
        _jsonArray = [[NSMutableArray alloc]init];
    }
    return _jsonArray;
}
- (SQCustomButton *)typeBtn{
    if (!_typeBtn) {
        _typeBtn = [[SQCustomButton alloc]initType:SQCustomButtonRightImageType imageSize:CGSizeMake(0, 0) midmargin:0];
        _typeBtn.text = SQNSLocalString(@"公开");
        _typeBtn.textColor = SQColor(@"#FF33B6");
        _typeBtn.tag = 1;
        _typeBtn.layer.cornerRadius = 13;
        _typeBtn.layer.masksToBounds = YES;
        _typeBtn.layer.borderColor = SQColor(@"#FF33B6").CGColor;
        _typeBtn.layer.borderWidth = 1;
        _typeBtn.font = FONT_REGULAR(14);
       
    }
    return _typeBtn;
}
- (HeaderView *)addButton{
    if (!_addButton) {
        _addButton = [[HeaderView alloc]init];
        _addButton.image = @"矩形";
        _addButton.colorString = @"#FFFFFF";
        [_addButton.btn addTarget:self action:@selector(SQ_addAnntionForMap) forControlEvents:UIControlEventTouchUpInside];
        _addButton.layer.cornerRadius = 6;
        _addButton.layer.masksToBounds = YES;
        _addButton.text = SQNSLocalString(@"确认添加");
        _addButton.font = FONT_MEDIUM(18);
    }
    return _addButton;
}

- (UILabel *)addressLabel{
    if (!_addressLabel) {
        _addressLabel = [[UILabel alloc]init];
//        _addressLabel.backgroundColor = SQHexColor(@"#000000", 0.3);
        _addressLabel.font = FONT_MEDIUM(16);
        _addressLabel.textColor = UIColor.whiteColor;
        _addressLabel.numberOfLines = 0;
        _addressLabel.textAlignment = NSTextAlignmentCenter;
//        _addressLabel.layer.cornerRadius = 2;
    }
    return _addressLabel;
}
@end
